<template>
  <el-menu
    class="el-menu-demo"
    mode="horizontal"
    :ellipsis="false"
    @select="handleSelect"
  >
    <!-- Logo -->
    <div class="logo-item">
      <a href="https://element-plus.org/zh-CN">
        <img
          style="width: 100px"
          src="@/assets/element-plus-logo.svg"
          alt="Element logo"
        />
      </a>
    </div>

    <!-- 搜索框 -->
    <div class="search-item">
      <el-autocomplete
        v-model="searchText"
        :fetch-suggestions="querySearch"
        popper-class="my-autocomplete"
        placeholder="请输入内容"
        @select="handleSelect"
      >
        <template #suffix>
          <el-icon class="el-input__icon" @click="handleIconClick">
            <Search />
          </el-icon>
        </template>
        <template #default="{ item }">
          <div class="value">{{ item.value }}</div>
          <span class="link">{{ item.link }}</span>
        </template>
      </el-autocomplete>
    </div>

    <!-- 头像 -->
    <el-dropdown class="avatar-menu" trigger="click">
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item @click="displayUserInfo = true"
            >个人信息</el-dropdown-item
          >
          <el-dropdown-item @click="editUserPassword = true"
            >修改密码</el-dropdown-item
          >
          <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
        </el-dropdown-menu>
      </template>
      <div class="avatar-wrapper">
        <el-avatar title="用户" :size="30" :src="personInfo.avatarUrl" />
      </div>
    </el-dropdown>

    <el-dialog v-model="displayUserInfo" width="40%" center>
      <template #header="{ close, titleId, titleClass }">
        <div class="my-header">
          <span :id="titleId" :class="titleClass"
            ><img
              style="width: 80px"
              src="@/assets/element-plus-logo.svg"
              alt="Element logo"
          /></span>
        </div>
      </template>
      <el-descriptions title="个人信息" direction="vertical" border>
        <template #extra>
          <el-button
            type="primary"
            @click="
              displayUserInfo = false;
              editUserInfo = true;
            "
            >修改信息</el-button
          >
        </template>
        <el-descriptions-item
          :rowspan="2"
          :width="140"
          label="头像"
          align="center"
        >
          <div class="avatar-container" @click="editAvatarVisible = true, displayUserInfo = false">
            <el-image
              style="width: 100px; height: 100px"
              :src="personInfo.avatarUrl"
            />
            <div class="avatar-overlay">
              <el-icon><Edit /></el-icon>
              <span>修改头像</span>
            </div>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="ID">{{
          personInfo.id
        }}</el-descriptions-item>
        <el-descriptions-item label="邮箱">{{
          personInfo.email
        }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag
            size="default"
            :type="
              personInfo.userStatus === '正常'
                ? 'success'
                : personInfo.userStatus === '异常'
                ? 'warning'
                : 'danger'
            "
          >
            {{ personInfo.userStatus }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="昵称">{{
          personInfo.nickname
        }}</el-descriptions-item>
        <el-descriptions-item label="个人简介">{{
          personInfo.biography
        }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <el-dialog v-model="editUserInfo" title="修改信息" width="500">
      <el-form :model="form">
        <el-form-item label="昵称" :label-width="formLabelWidth">
          <el-input v-model="form.nickname" autocomplete="off" />
        </el-form-item>
        <el-form-item label="个人简介" :label-width="formLabelWidth">
          <el-input
            v-model="form.biography"
            type="textarea"
            :rows="3"
            placeholder="请输入个人简介"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editUserInfo = false">取消</el-button>
          <el-button type="primary" @click="handleUpdateUserInfo">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 头像上传对话框 -->
    <el-dialog v-model="editAvatarVisible" title="修改头像" width="400" center>
      <div class="avatar-upload-container">
        <el-upload
          class="avatar-uploader"
          action="#"
          :show-file-list="false"
          :auto-upload="false"
          :on-change="handleAvatarChange"
        >
          <img v-if="form.avatarUrl" :src="form.avatarUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
        <div class="upload-tip">点击上方区域上传新头像</div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editAvatarVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpdateAvatar">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="editUserPassword" title="修改密码" width="400">
      <el-form :model="passwordForm">
        <el-form-item label="新密码" :label-width="formLabelWidth">
          <div class="password-input-container">
            <el-input
              v-model="passwordForm.newPassword"
              :type="showPassword ? 'text' : 'password'"
              autocomplete="off"
            />
            <el-icon
              class="password-toggle-icon"
              :class="{ active: showPassword }"
              @click="togglePasswordVisibility('password')"
            >
              <Opportunity />
            </el-icon>
          </div>
        </el-form-item>
        <el-form-item label="确认新密码" :label-width="formLabelWidth">
          <div class="password-input-container">
            <el-input
              v-model="passwordForm.confirmPassword"
              :type="showConfirmPassword ? 'text' : 'password'"
              autocomplete="off"
            />
            <el-icon
              class="password-toggle-icon"
              :class="{ active: showConfirmPassword }"
              @click="togglePasswordVisibility('confirm')"
            >
              <Opportunity />
            </el-icon>
          </div>
        </el-form-item>
        <el-form-item label="验证码" :label-width="formLabelWidth">
          <div class="verification-code-wrapper">
            <el-input
              v-model="passwordForm.verificationCode"
              autocomplete="off"
            />
            <el-button @click="sendVerificationCodeByUpdatePassword"
              >发送验证码</el-button
            >
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editUserPassword = false">取消</el-button>
          <el-button type="primary" @click="submitPasswordForm">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 设置盒子 -->
    <el-dropdown class="settings-menu" trigger="click">
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item>深色模式</el-dropdown-item>
          <el-dropdown-item>浅色模式</el-dropdown-item>
        </el-dropdown-menu>
      </template>
      <el-icon title="设置" :size="24">
        <Setting />
      </el-icon>
    </el-dropdown>
  </el-menu>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { Search, Setting, Opportunity, Plus, Edit } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import {
  logout,
  getAuthHeader,
  sendVerificationCodeByUpdatePasswordAPI,
  getUserInfo,
  updateUserPassword,
  updateUserAvatar,
  updateUserInfo,
} from "@/api";
import { useRouter } from "vue-router";
import axios from "axios";
import { useMenuStore } from "@/stores/menuStore";

const router = useRouter();
const menuStore = useMenuStore();

const displayUserInfo = ref(false);
const editUserInfo = ref(false);
const editUserPassword = ref(false);
const editAvatarVisible = ref(false);

const searchText = ref("");

const handleSelect = (item) => {
  if (item.link) {
    menuStore.setActiveMenu(item.link);
    router.push(item.link);
  }
};

const handleLogout = () => {
  logout(router);
};

const personInfo = reactive({
  id: "",
  email: "",
  nickname: "",
  avatarUrl: "",
  biography: "",
  userStatus: "",
});

const form = reactive({
  nickname: personInfo.nickname,
  biography: personInfo.biography,
  avatarUrl: personInfo.avatarUrl,
});
const formLabelWidth = "120px";

const passwordForm = reactive({
  email: "",
  newPassword: "",
  confirmPassword: "",
  verificationCode: "",
});

const showPassword = ref(false);
const showConfirmPassword = ref(false);

const togglePasswordVisibility = (field) => {
  if (field === "password") {
    showPassword.value = !showPassword.value;
  } else {
    showConfirmPassword.value = !showConfirmPassword.value;
  }
};

const validatePasswordForm = () => {
  if (!passwordForm.newPassword || !passwordForm.confirmPassword) {
    ElMessage.warning("密码不能为空");
    return false;
  }
  if (
    passwordForm.newPassword.length < 6 ||
    passwordForm.confirmPassword.length < 6
  ) {
    ElMessage.warning("密码长度不能小于6位");
    return false;
  }
  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    ElMessage.warning("两次输入的密码不一致");
    return false;
  }
  return true;
};

let email = ref("");

const sendVerificationCodeByUpdatePassword = async () => {
  if (!validatePasswordForm()) {
    return;
  }
  const result = await sendVerificationCodeByUpdatePasswordAPI();
  if (result) {
    email.value = result;
  }
};

const submitPasswordForm = async () => {
  if (!validatePasswordForm()) {
    return;
  }
  if (!email.value) {
    ElMessage.warning("请先发送验证码");
    return;
  }
  const success = await updateUserPassword(
    email.value,
    passwordForm.newPassword,
    passwordForm.verificationCode,
    router
  );
  if (success) {
    editUserPassword.value = false;
    // 清空表单
    passwordForm.newPassword = "";
    passwordForm.confirmPassword = "";
    passwordForm.verificationCode = "";
    email.value = "";
  }
};

const handleAvatarChange = (file) => {
  form.avatarUrl = URL.createObjectURL(file.raw);
};

const handleUpdateUserInfo = async () => {
  const success = await updateUserInfo(form.nickname, form.biography, router);
  if (success) {
    editUserInfo.value = false;
    // 更新成功后重新获取用户信息以刷新显示
    const userInfo = await getUserInfo(router);
    if (userInfo) {
      personInfo.nickname = userInfo.nickname;
      personInfo.biography = userInfo.biography;
    }
  }
};

const handleUpdateAvatar = async () => {
  if (!form.avatarUrl) {
    ElMessage.warning('请先选择要上传的头像');
    return;
  }

  // 从 form.avatarUrl 中获取文件对象
  const file = await fetch(form.avatarUrl)
    .then(r => r.blob())
    .then(blobFile => new File([blobFile], 'avatar.png', { type: 'image/png' }));

  const success = await updateUserAvatar(file, router);
  if (success) {
    editAvatarVisible.value = false;
    // 更新头像成功后重新获取用户信息以刷新头像
    const userInfo = await getUserInfo(router);
    if (userInfo) {
      personInfo.avatarUrl = userInfo.avatarUrl;
      form.avatarUrl = userInfo.avatarUrl;
    }
  }
};

const links = ref([
  { value: "首页", link: "/" },
  { value: "流量分析-天级别", link: "/trafficByDay" },
  { value: "流量分析-小时级别", link: "/trafficByHour" },
  { value: "流量分析-用户行为", link: "/trafficByUserBehavior" },
  { value: "转化率分析", link: "/convertionRate" },
  { value: "用户价值-ARPU分析", link: "/userArpuAndArppu" },
  { value: "用户价值-复购分析", link: "/userRepeatBuy" },
  { value: "聚类分析-特征分析", link: "/clusteringFeature" },
  { value: "聚类分析-结果分析", link: "/clusterAnalysisResults" },
]);

const querySearch = (queryString, cb) => {
  const results = queryString
    ? links.value.filter(createFilter(queryString))
    : links.value;
  cb(results);
};

const createFilter = (queryString) => {
  return (link) => {
    return link.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0;
  };
};

const handleIconClick = (ev) => {
  console.log(ev);
};

const loadAll = () => {
  return [
    { value: "首页", link: "/" },
    { value: "流量分析-天级别", link: "/trafficByDay" },
    { value: "流量分析-小时级别", link: "/trafficByHour" },
    { value: "流量分析-用户行为", link: "/trafficByUserBehavior" },
    { value: "转化率分析", link: "/convertionRate" },
    { value: "用户价值-ARPU分析", link: "/userArpuAndArppu" },
    { value: "用户价值-复购分析", link: "/userRepeatBuy" },
    { value: "聚类分析-特征分析", link: "/clusteringFeature" },
    { value: "聚类分析-结果分析", link: "/clusterAnalysisResults" },
  ];
};

onMounted(async () => {
  links.value = loadAll();
  const userInfo = await getUserInfo(router);
  if (userInfo) {
    personInfo.id = userInfo.id;
    personInfo.email = userInfo.email;
    personInfo.nickname = userInfo.nickname;
    personInfo.avatarUrl = userInfo.avatarUrl;
    personInfo.biography = userInfo.biography;
    personInfo.userStatus = userInfo.userStatus;

    // 更新表单数据
    form.nickname = userInfo.nickname;
    form.email = userInfo.email;
    form.biography = userInfo.biography;
  }
});
</script>

<style scoped>
.el-menu-demo {
  padding: 20px;
  display: flex;
  align-items: center;
}

/* Logo 样式 */
.logo-item {
  display: flex;
  margin: 0 40px;
}

.logo-item a:hover {
  border-bottom: #409eff 2px solid;
  text-decoration: none;
}

/* 搜索框样式 */
.search-item {
  margin-left: auto;
  display: flex;
  max-width: 280px;
  justify-content: end;
  align-items: end;
  text-align: right;
}

:deep(.el-autocomplete .el-input__wrapper) {
  border-radius: 16px;
}

.my-autocomplete li {
  line-height: normal;
  padding: 7px;
}

.my-autocomplete li .value {
  text-overflow: ellipsis;
  overflow: hidden;
}

.my-autocomplete li .link {
  font-size: 12px;
  color: #b4b4b4;
}

.my-autocomplete li .highlighted .link {
  color: #ddd;
}

/* 头像菜单样式 */
.avatar-menu {
  cursor: pointer;
  margin-left: 20px;
}

/* 设置菜单样式 */
.settings-menu {
  cursor: pointer;
  margin-left: 20px;
  transition: color 0.3s;
}

.settings-menu:hover {
  color: #409eff;
}

.verification-code-wrapper {
  display: flex;
  align-items: center;
}

.verification-code-wrapper .el-input {
  flex: 1;
  margin-right: 10px;
}

.password-input-wrapper {
  position: relative;
  display: flex;
  align-items: center;
}

.password-toggle-icon {
  position: absolute;
  right: 10px;
  cursor: pointer;
  color: #909399;
}

.password-toggle-icon.active {
  color: #409eff;
}

.password-toggle-icon:hover {
  opacity: 0.8;
}

.password-input-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.password-input-container .el-input {
  flex: 1;
}

.password-toggle-icon {
  cursor: pointer;
  color: #909399;
  font-size: 20px;
}

.password-toggle-icon.active {
  color: #409eff;
}

.password-toggle-icon:hover {
  opacity: 0.8;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader .avatar {
  width: 100px;
  height: 100px;
  display: block;
  border-radius: 50%;
}

.avatar-uploader .el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
}

.avatar-uploader .el-icon.avatar-uploader-icon::after {
  content: '上传头像';
  font-size: 12px;
  position: absolute;
  bottom: 15px;
  left: 50%;
  transform: translateX(-50%);
}

.el-icon.avatar-uploader-icon:hover {
  border-color: #409EFF;
}

.avatar-container {
  position: relative;
  width: 100px;
  height: 100px;
  margin: 0 auto;
  cursor: pointer;
  border-radius: 50%;
  overflow: hidden;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s;
  color: white;
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
}

.avatar-overlay .el-icon {
  font-size: 24px;
  margin-bottom: 8px;
}

.avatar-upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}

.upload-tip {
  margin-top: 10px;
  color: #909399;
  font-size: 14px;
}

.avatar-uploader {
  text-align: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}
</style>
